﻿
DECLARE @Now datetime
DECLARE @InSessionKey varchar(48)

SET @Now = '$NOW$'
SET @InSessionKey = '$IN_SESSION_KEY$'

DECLARE @SessionKey varchar(48)
DECLARE @LoginTime datetime
DECLARE @Data varchar(max)
DECLARE @Expires int
DECLARE @AccessTime datetime
DECLARE @ExpiresTime datetime
DECLARE @ClearStartTime datetime
DECLARE @ClearEndTime datetime

IF(@Now BETWEEN @ClearStartTime AND @ClearEndTime) BEGIN
	DELETE CoSessions WHERE @Now > @ExpiresTime
END

SELECT
	@SessionKey = SessionKey,
	@LoginTime = LoginTime,
	@Data = Data,
	@Expires = Expires,
	@AccessTime = AccessTime,
	@ExpiresTime = ExpiresTime
FROM CoSessions
WHERE SessionKey = @InSessionKey

if(@SessionKey IS NULL) BEGIN
	RETURN;
END

IF(@Now > @ExpiresTime) BEGIN
	DELETE CoSessions WHERE SessionKey = @SessionKey
	RETURN;
END

IF(@Expires IS NULL OR @Expires = 0) BEGIN
	UPDATE CoSessions
	SET AccessTime = @Now
	FROM CoSessions WHERE SessionKey = @SessionKey
END ELSE BEGIN
	UPDATE CoSessions
	SET AccessTime = @Now,
		ExpiresTime = DATEADD(MI, @Expires, @Now)
	FROM CoSessions WHERE SessionKey = @SessionKey
END

SELECT * FROM CoSessions WHERE SessionKey = @SessionKey

